/**
 * @Auther: ayo
 * @Date: 2018/8/22 18:02
 * @Description: 正则校验工具类
 */
import { FormControl } from '@angular/forms';
import { AlertProvider } from './alertUtil';
import { Injectable } from '@angular/core';
import { Utils } from './utils';

@Injectable({
    providedIn: 'root'
})
export class ValidProvider {

    // 身份证最后一位验证权重
    weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

    constructor(private alertProvider: AlertProvider) {
    }

    static isValid(control: FormControl) {

        if (control.value.match(/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/)) {
            return null;
        }

        if (control.value.match(/^1[3|4|5|7|8][0-9]{9}$/)) {
            return null;
        }

        return {invalidAccount: true};
    }

    static isValidPhone(control: FormControl) {

        if (control.value.match(/^1[3|4|5|7|8][0-9]{9}$/)) {
            return null;
        }

        return {invalidAccount: true};
    }

    static isValidEmail(control: FormControl) {

        if (control.value.match(/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/)) {
            return null;
        }

        return {invalidAccount: true};
    }

    /**
     * @Author: ayo
     * @Date: 2018/11/22 10:55
     * @Param:
     * @return:
     * @Description: // 验证证件号最后一位值
     **/
    verifyIdCard = (idCard) => {
        if (15 === idCard.length) {
            return true;
        }
        const lastNo = idCard.substring(17, 18);
        let sum = 0;
        for (let i = 0; i < 17; i++) {
            sum += idCard.substring(i, i + 1) * this.weights[i];
        }
        switch (sum % 11) {
            case 0:
                if ('1' !== lastNo) {
                    return false;
                }
                break;
            case 1:
                if ('0' !== lastNo) {
                    return false;
                }
                break;
            case 2:
                if ('X' !== lastNo && 'x' !== lastNo) {
                    return false;
                }
                break;
            case 3:
                if ('9' !== lastNo) {
                    return false;
                }
                break;
            case 4:
                if ('8' !== lastNo) {
                    return false;
                }
                break;
            case 5:
                if ('7' !== lastNo) {
                    return false;
                }
                break;
            case 6:
                if ('6' !== lastNo) {
                    return false;
                }
                break;
            case 7:
                if ('5' !== lastNo) {
                    return false;
                }
                break;
            case 8:
                if ('4' !== lastNo) {
                    return false;
                }
                break;
            case 9:
                if ('3' !== lastNo) {
                    return false;
                }
                break;
            case 10:
                if ('2' !== lastNo) {
                    return false;
                }
                break;
            default:
                break;
        }
        return true;
    };

    verificationIdCardAndBirthday = (firstModelName, lastModelName, alertText) => {
        if (firstModelName.replace(new RegExp('-', 'g'), '') !== (lastModelName.length === 15 ? '19' + lastModelName.substring(6, 12) : lastModelName.substring(6, 14))) {
            this.alertProvider.alert(alertText);
            return false;
        }
        return true;
    };

    // 图片验证码功能API
    getGVerify = (id) => {
        // 创建一个图形验证码对象，接收options对象为参数
        function GVerify(options) {
            // 默认options参数值
            // 容器Id
            // canvas的ID
            // 默认canvas宽度
            // 默认canvas高度
            // 图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
            this.options = {
                id: '', canvasId: 'verifyCanvas', width: '120', height: '43', type: 'blend', code: ''
            };

            // 判断传入参数类型
            if (Object.prototype.toString.call(options) === '[object Object]') {
                for (const key in options) {
                    if (options.hasOwnProperty(key)) {
                        switch (key) {
                            case key:
                                // 根据传入的参数，修改默认参数值
                                this.options[key] = options[key];
                                break;
                            default:
                                break;
                        }
                    }
                }
            } else {
                this.options.id = options;
            }

            this.options.numArr = '0,1,2,3,4,5,6,7,8,9'.split(',');
            this.options.letterArr = getAllLetter();

            this._init();
            this.refresh();
        }

        GVerify.prototype = {
            /**版本号**/
            version: '1.0.0',

            /**初始化方法**/
            _init: function() {
                const con = document.getElementById(this.options.id);
                const canvas = document.createElement('canvas');
                canvas.id = this.options.canvasId;
                canvas.width = this.options.width;
                canvas.height = this.options.height;
                canvas.style.cssFloat = 'right';
                canvas.style.cursor = 'pointer';
                canvas.innerHTML = '您的浏览器版本不支持canvas';
                con.appendChild(canvas);
                const parent = this;
                canvas.onclick = function() {
                    // 新建
                    parent.options.callback();
                };
            },

            /**生成验证码**/
            refresh: function() {
                let newCodeFlag = false;
                if (Utils.isNotEmpty(this.options.code)) {
                    newCodeFlag = true;
                } else {
                    this.options.code = '';
                }
                const canvas = <HTMLCanvasElement>document.getElementById(this.options.canvasId);
                let ctx;
                if (canvas.getContext) {
                    ctx = canvas.getContext('2d');
                }
                ctx.textBaseline = 'middle';

                ctx.fillStyle = randomColor(180, 240);
                ctx.fillRect(0, 0, this.options.width, this.options.height);

                let txtArr;
                // 判断验证码类型
                if (this.options.type === 'blend') {
                    txtArr = this.options.numArr.concat(this.options.letterArr);
                } else if (this.options.type === 'number') {
                    txtArr = this.options.numArr;
                } else {
                    txtArr = this.options.letterArr;
                }

                for (let i = 1; i <= 4; i++) {
                    let txt;
                    if (!newCodeFlag) {
                        txt = txtArr[randomNum(0, txtArr.length)];
                        this.options.code += txt;
                    } else {
                        txt = this.options.code[i - 1];
                    }
                    ctx.font = '20px SimHei';
                    // 随机生成字体大小
                    // ctx.font = randomNum(this.options.height/2, this.options.height) + 'px SimHei';
                    // 随机生成字体颜色
                    ctx.fillStyle = randomColor(50, 160);
                    /* ctx.shadowOffsetX = randomNum(-3, 3);
                     ctx.shadowOffsetY = randomNum(-3, 3);*/
                    ctx.shadowBlur = randomNum(-3, 3);
                    ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
                    const x = this.options.width / 5 * i;
                    const y = this.options.height / 2;
                    const deg = randomNum(-30, 30);
                    /**设置旋转角度和坐标原点**/
                    ctx.translate(x, y);
                    ctx.rotate(deg * Math.PI / 180);
                    ctx.fillText(txt, 0, 0);
                    /**恢复旋转角度和坐标原点**/
                    ctx.rotate(-deg * Math.PI / 180);
                    ctx.translate(-x, -y);
                }
                /**绘制干扰线**/
                for (let i = 0; i < 4; i++) {
                    ctx.strokeStyle = randomColor(40, 180);
                    ctx.beginPath();
                    ctx.moveTo(randomNum(0, this.options.width / 2), randomNum(0, this.options.height / 2));
                    ctx.lineTo(randomNum(0, this.options.width / 2), randomNum(0, this.options.height));
                    ctx.stroke();
                }
                /**绘制干扰点**/
                for (let i = 0; i < this.options.width / 4; i++) {
                    ctx.fillStyle = randomColor(0, 255);
                    ctx.beginPath();
                    ctx.arc(randomNum(0, this.options.width), randomNum(0, this.options.height), 1, 0, 2 * Math.PI);
                    ctx.fill();
                }
            },

            /**验证验证码**/
            validate: function(code) {
                const verifyCode = code.toLowerCase();
                const v_code = this.options.code.toLowerCase();
                return verifyCode === v_code;
            }
        };

        /**生成字母数组**/
        function getAllLetter() {
            const letterStr = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
            return letterStr.split(',');
        }

        /**生成一个随机数**/
        function randomNum(min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        }

        /**生成一个随机色**/
        function randomColor(min, max) {
            const r = randomNum(min, max);
            const g = randomNum(min, max);
            const b = randomNum(min, max);
            return 'rgb(' + r + ',' + g + ',' + b + ')';
        }

        return new GVerify(id);
    };

    getSimpleVerify = (code) => {
        document.getElementById('verifyCode').style.color = '#009DDC';
        document.getElementById('verifyCode').style.marginTop = '10px';
        document.getElementById('verifyCode').style.marginLeft = '21%';
        document.getElementById('verifyCode').style.display = 'inline-block';
        document.getElementById('verifyCode').style.letterSpacing = '4px';
        document.getElementById('verifyCode').style.fontFamily = 'Fixedsys';
        document.getElementById('verifyCode').innerHTML = code;
    };

    validateSimpleVerify = (code) => {
        return document.getElementById('verifyCode').innerText.toLowerCase() === code.toLowerCase();
    };
}
